import React, { useState } from 'react';
import { Button as AntButton, Modal, Upload, message } from 'antd';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import 'antd/dist/reset.css';

const ImageUploader = (props) => {
  const { 
    buttonText = "上传图片", 
    modalTitle = "图片上传", 
    onUploadSuccess,
    onUploadError,
    customRequest,  // 自定义上传请求
    action,         // 上传地址
    headers,        // 上传请求头
    data,           // 上传额外参数
    withCredentials,// 是否携带cookie
    ...restProps 
  } = props;
  
  const [visible, setVisible] = useState(false);
  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);

  const showModal = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setFileList([]);
  };

  const beforeUpload = (file) => {
    // 文件类型检查
    const isImage = file.type && file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
    }
    
    // 文件大小检查 (限制 2MB)
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于 2MB!');
    }
    
    // 如果是图片且小于2MB则允许上传
    return isImage && isLt2M ? true : Upload.LIST_IGNORE;
  };
  
  const handleChange = ({ fileList, file }) => {
    // 限制只能上传图片
    const imageFiles = fileList.filter(file => {
      if (file.originFileObj && file.originFileObj.type && !file.originFileObj.type.startsWith('image/')) {
        message.error('只能上传图片文件!');
        return false;
      }
      return true;
    });
    
    setFileList(imageFiles);
  };

  const handleUpload = () => {
    if (fileList.length === 0) {
      message.warning('请选择要上传的图片');
      return;
    }

    setUploading(true);
    
    // 如果提供了自定义上传请求
    if (customRequest) {
      const customOptions = {
        fileList,
        onSuccess: (response) => {
          setUploading(false);
          setVisible(false);
          setFileList([]);
          
          // 触发上传成功回调
          if (onUploadSuccess) {
            onUploadSuccess(response, fileList);
          }
          
          message.success('图片上传成功');
        },
        onError: (error) => {
          setUploading(false);
          if (onUploadError) {
            onUploadError(error);
          }
          message.error('图片上传失败');
        }
      };
      
      customRequest(customOptions);
      return;
    }
    
    // 如果提供了上传地址，使用 Upload 组件的默认上传
    if (action) {
      // 通过手动触发 Upload 组件的上传
      const formData = new FormData();
      
      // 添加额外数据
      if (data) {
        Object.keys(data).forEach(key => {
          formData.append(key, data[key]);
        });
      }
      
      // 添加文件
      fileList.forEach(file => {
        formData.append('file', file.originFileObj);
      });
      
      // 创建上传请求
      const xhr = new XMLHttpRequest();
      
      xhr.onload = () => {
        if (xhr.status === 200 || xhr.status === 201) {
          setUploading(false);
          setVisible(false);
          setFileList([]);
          
          let response;
          try {
            response = JSON.parse(xhr.responseText);
          } catch (e) {
            response = xhr.responseText;
          }
          
          // 触发上传成功回调
          if (onUploadSuccess) {
            onUploadSuccess(response, fileList);
          }
          
          message.success('图片上传成功');
        } else {
          setUploading(false);
          if (onUploadError) {
            onUploadError(new Error(`Upload failed with status ${xhr.status}`));
          }
          message.error('图片上传失败');
        }
      };
      
      xhr.onerror = () => {
        setUploading(false);
        if (onUploadError) {
          onUploadError(new Error('Network error'));
        }
        message.error('网络错误，上传失败');
      };
      
      // 设置请求头
      if (headers) {
        Object.keys(headers).forEach(key => {
          xhr.setRequestHeader(key, headers[key]);
        });
      }
      
      // 设置是否携带凭证
      if (withCredentials) {
        xhr.withCredentials = true;
      }
      
      // 发送请求
      xhr.open('POST', action, true);
      xhr.send(formData);
      return;
    }
    
    // 默认行为：模拟上传过程
    setTimeout(() => {
      setUploading(false);
      setVisible(false);
      setFileList([]);
      
      // 触发上传成功回调
      if (onUploadSuccess) {
        onUploadSuccess({ message: 'Upload successful (simulated)' }, fileList);
      }
      
      message.success('图片上传成功');
    }, 2000);
  };

  const uploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload,
    fileList,
    onChange: handleChange,
    listType: 'picture',
    maxCount: 5, // 最多上传5张图片
    // 如果提供了上传地址，使用 Upload 组件的默认上传功能
    ...(action && !customRequest ? { 
      action,
      headers,
      data,
      withCredentials,
      showUploadList: true
    } : {
      showUploadList: true
    })
  };

  return (
    <>
      <AntButton 
        icon={<UploadOutlined />} 
        onClick={showModal} 
        {...restProps}
      >
        {buttonText}
      </AntButton>
      
      <Modal
        title={modalTitle}
        open={visible}
        onOk={handleUpload}
        onCancel={handleCancel}
        okText="上传"
        cancelText="取消"
        okButtonProps={{ loading: uploading }}
      >
        <Upload.Dragger {...uploadProps}>
          <p className="ant-upload-drag-icon">
            <PlusOutlined />
          </p>
          <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
          <p className="ant-upload-hint">
            支持单次上传最多5张图片，单张图片不超过2MB
          </p>
        </Upload.Dragger>
      </Modal>
    </>
  );
};

ImageUploader.displayName = 'ImageUploader';

export default ImageUploader;